import { Card, Layout as AntdLayout, Image, Collapse, Button, Descriptions, Tag, message } from 'antd'
import { Time, ArrowUpRight } from '@carbon/icons-react'
import highlight from '@bytemd/plugin-highlight-ssr'
import gfm from '@bytemd/plugin-gfm'
import PanelEmpty from '@/components/PanelEmpty'
import { EyeOutlined } from '@ant-design/icons'
import 'highlight.js/styles/github-dark.css'
import { useRouter } from 'next/router'
import { Viewer } from '@bytemd/react'
import Layout from '@/layouts/default'
import { fetchArticle } from '@/api'
import AppConfig from '@/config'
import Head from 'next/head'
import Link from 'next/link'
import ShareBar from '@/components/ShareBar'
import PostAnchor from '@/components/Post/Anchor'
import { useEffect, useState } from 'react'
import { isBrowser } from '@/utils'

const { title } = AppConfig
const { Content, Sider } = AntdLayout
const { Panel } = Collapse

type PageProps = {
  data: any
}

export default function Detail({ data }: PageProps) {
  const { github, gitee, homepage, md, likeCount } = data
  const url = github || gitee
  const router = useRouter()
  const { id = 0 } = router.query
  const LikeStoreKey = 'react.admin.cn.likes.ids'
  const [isLiked, setIsLiked] = useState<any>(false)
  const [likedIds, setlikedIds] = useState<any>([])
  // 检查是否赞过
  const checkLiked = (ided: number) => likedIds.includes(ided)

  const initLike = () => {
    if (isBrowser()) {
      const ids = JSON.parse(localStorage.getItem(LikeStoreKey) || '[]')
      setlikedIds(ids)

      if (ids.includes(+id)) {
        setIsLiked(true)
      }
    }
  }

  useEffect(() => {
    initLike()
  }, [])

  const extra = (
    <span className="time">
      <Time className="mr-2" />{data.createTime}
    </span>
  )
  const plugins: any = [highlight(), gfm()]

  // 处理点赞成功
  const handleLikeOk = ({ id: newId }: any) => {
    if (isBrowser()) {
      const newLikedIds = likedIds.length ? [...likedIds, newId] : [newId]
      setlikedIds(newLikedIds)

      localStorage.setItem(LikeStoreKey, JSON.stringify(newLikedIds))

      message.success('点赞 +1')
    }
  }

  // 处理点赞
  const onLike = (count:number) => {
    if (checkLiked(+id)) {
      message.warning('感谢支持，您已赞过~！')
      return
    }

    fetchArticle({ id, params: { likeCount: count }, type: 'patch' }).then((res) => {
      res ? handleLikeOk(res) : message.error(res?.error || '点赞失败，请稍候在试~！')
    })
  }

  return (
    <Layout>
      <Head>
        <title>{`${data.title} - ${title}`}</title>
      </Head>
      <div className="app-page-detail bg-gray-100 relative">
        <ShareBar isLiked={isLiked} likeCount={likeCount} handleLike={onLike} />
        <AntdLayout className="container mx-auto">
          <Content>
            <Card title={data.title} className="app-detail-header mb-5" hoverable bordered={false} extra={extra}>
              <div className="center">
                <Image src={data.coverUrl} />
              </div>
            </Card>
            <Card title="README">
              <div className="app-readme-content">
                <Viewer value={md} plugins={plugins} />
              </div>
            </Card>
          </Content>
          <Sider width={350} theme="light" className="my-5 app-aside-collapse pt-5">
            <Card title="简介" bordered={false} className="app-aside-card mb-8" hoverable>
              <Collapse defaultActiveKey={['1', '2', '3', '4']} ghost className="app-editor-collapse" expandIconPosition="end">
                <Panel header="介绍" key="1">
                  <div className="mb-3 panel-introduction">{data.summary}</div>
                  <Link href={url} target="_blank">
                    <Button type="primary" shape="round" icon={<EyeOutlined />}>查看仓库</Button>
                  </Link>
                </Panel>
                <Panel header="基本信息" key="2" className="app-collapse-base">
                  <Descriptions column={2}>
                    <Descriptions.Item label="作者">
                      { homepage ? <Link target="_blank" href={homepage}>{data.author}</Link> : data.author}
                    </Descriptions.Item>
                    <Descriptions.Item label="版本">{data.version}</Descriptions.Item>
                    <Descriptions.Item label="浏览量">{data.viewsCount}</Descriptions.Item>
                    <Descriptions.Item label="加入时间">{data.createTime?.slice(0, 11)}</Descriptions.Item>
                  </Descriptions>
                </Panel>
                <Panel header="标签" key="3">
                  <div className="app-tags-list">
                    {data?.tags?.length > 0 && data.tags.map((tag: any) => {
                      return (
                        <Link key={tag.id} target="_blank" href={tag.tagUrl}>
                          <Tag color="magenta" className="ml-2 mb-2" key={tag.id}>{ tag.tagName }<ArrowUpRight className="link" /></Tag>
                        </Link>
                      )
                    })}
                    {!data?.tags?.length && <PanelEmpty />}
                  </div>
                </Panel>
                <Panel header="后台语言" key="4">
                  {data?.backend?.length > 0 && data.backend.map((back: any) => {
                    return (
                      <Tag color="volcano" className="ml-2 mb-2" key={back.id}>{ back.backendName }</Tag>
                    )
                  })}
                  {!data?.backend?.length && <PanelEmpty />}
                </Panel>
              </Collapse>
            </Card>
            <Card title="目录" bordered={false} className="app-sider-anchor mb-8 sticky" hoverable>
              <PostAnchor />
            </Card>
          </Sider>
        </AntdLayout>
      </div>
    </Layout>
  )
}

export async function getServerSideProps({ query }: any) {
  const { id } = query
  const data = await fetchArticle({ id })

  return { props: { data } }
}
